<?php

namespace GuanChanghu\Library\Http\Controllers;

use GuanChanghu\Configs\FieldConfig;
use GuanChanghu\Exceptions\UserException;
use GuanChanghu\Library\Facades\Auth;
use GuanChanghu\Library\Facades\Client;
use GuanChanghu\Library\Facades\Upload;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use Throwable;

/**
 * @author 管昌虎
 * Class UploadController
 * @tag encryption free
 * @package GuanChanghu\Library\Http\Controllers
 * Created on 2022/4/9 16:52
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
class UploadController extends Controller
{
    /**
     * @param Request $request
     * @param string $client
     * @return array
     */
    public function index(Request $request, string $client): array
    {
        try {
            // 这里判断是否登录
            $user = Auth::resolve($client);

            if (!$user) {
                throw new UserException(__('guan-changhu::auth.login.error.no'));
            }

            Client::checkMillisecondTimestamp($request->input('timestamp', 0));

            Client::throttle((int)($request->input('timestamp', 0) / 1000), (int)$request->input('random', 0), $user);

            $fileStoreRecord = Upload::upload($user, $request);

            return [
                'success' => true,
                'module' => $fileStoreRecord['module'],
                'interface' => 0,
                'code' => FoundationResponse::HTTP_OK,
                FieldConfig::DATA_FIELD => [
                    'path' => $fileStoreRecord['path'],
                    'relative' => $fileStoreRecord['relative'],
                ],
            ];
        } catch (Throwable $throwable) {
            // 不在合法的客户端
            return [
                'success' => false,
                'code' => $throwable->getCode(),
                FieldConfig::MESSAGE_FIELD => $throwable->getMessage(),
            ];
        }
    }
}
